var _INDEX = '0';
var _TYPE = 'MerchantWords:Search A+ Keyword List';

function log(msg,level = config.LOG._LOG_LEVEL_DEBUG) {
    logger.out(`{${_TYPE} (index:${_INDEX})} ` + msg,level)
}

function parser() {
    let result = {
        rows :{
            detailInfo:[],
            list:[],
            summary:'',
            total:0,
            page:0
        },
        code:Const._RETCODE_SUCCESS
    };
    //解析头部数据
    result.rows.detailInfo = parserDetailInfo();
    //解析表格数据
    result.rows.summary = parserSummary();
    //解析列表数据
    result.rows.list = parserList();
    //解析最大页码
    result.rows.total = getMaxPage();
    //解析当前页
    result.rows.page = getCurrentPage();
    return result;
}

/**
 * 解析summary数据
 */
function parserSummary() {
    let scriptContent = '';
    $('script').each(function () {
        let prefix = 'let G_asinPositionDetailData';
        scriptContent = $(this).html();
        if(scriptContent && scriptContent.indexOf(prefix) !== -1){
            scriptContent = scriptContent.replace(prefix + ' = ','');
            scriptContent = eval('('+scriptContent+')');
            return false;
        }
    });
    return scriptContent;
}

/**
 * 解析列表数据
 */
function parserList() {
    let result = [];
    let list = $('#resultsTable > tbody > tr');
    if(!list || list.length === 0){
        return result;
    }

    //#resultsTable > tbody > tr:nth-child(1) > td.table__col-size9 > div > div > div > ul > li.keywords > span > a:nth-child(1)
    for(let i = 0; i < list.length; i++){
        let dom = list[i];
        //关键字列表
        let keywordInfo = parserTeamsList(dom);
        let keywordId = parserKeywordId(dom);
        let volume = $(dom).find('td:nth-child(2)').text();
        let rank = $(dom).find('td:nth-child(3)').text();
        let results = $(dom).find('td:nth-child(4)').text();
        let reviews = $(dom).find('td:nth-child(5)').text();
        let choice = $(dom).find('td:nth-child(6)').text();
        result.push({
            teams:keywordInfo,
            volume:volume,
            rank:rank,
            results:results,
            reviews:reviews,
            choice:choice,
            keywordId:keywordId
        })
    }
    return result;
}

function parserKeywordId(dom) {
    return $(dom).find('td.table__col-size9 > div > div > div > ul > li:nth-child(3) > a').attr('data-keywordid');
}

/**
 * 获取最大页
 */
function getMaxPage() {
    let doms = $('body > div.wrapper.wrapper--alt > section > div.container__section > div.section__actions > nav > ul > li');
    let length = doms.length;
    if(length < 2){
        return 1;
    }
    let page = $(doms[length - 2]).find('a').text();
    return utils.special(page);
}

/**
 * 获取当前页
 */
function getCurrentPage() {
    // let dom = $('body > div.wrapper.wrapper--alt > section > div.container__section > div.section__actions > nav > ul > button');
    // log(`Page:${dom}`);
    return 0;
}

function parserTeamsList(dom) {
    let result = [];
    let ds = $(dom).find('td.table__col-size9 > div > div > div > ul > li.keywords > span > a');
    for(let i = 0; i < ds.length; i++){
        result.push({
            keyword:$(ds[i]).text(),
            href: $(ds[i]).attr('href')
        });
    }
    return result;
}

function parserDetailInfo() {
    let image = parserImage();
    let keyword = parserKeyword();
    let by = parserByInfo();
    let title = parserTitle();
    let href = parserHref();
    let price = parserPrice();
    let teams = parserTeams();
    let rating = parserRating();
    let reviews = parserReviews();
    let badge = parserBadge();
    return {
        image:image,
        keyword:keyword,
        by:by,
        title:title,
        href:href,
        price:price,
        teams:teams,
        rating:rating,
        reviews:reviews,
        badge:badge
    }
}

function parserBadge() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > div > div > div:nth-child(5) > p').text();
}

function parserReviews() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > div > div > div:nth-child(4) > p').text();
}

function parserRating() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > div > div > div:nth-child(3) > p').text();
}

function parserTeams() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > div > div > div:nth-child(2) > p').text()
}

function parserPrice() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > div > div > div:nth-child(1) > p').text();
}

function parserHref() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > a.title.expand-name').attr('href');
}

function parserTitle() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > a.title.expand-name > h4').text()
}

function parserByInfo() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > a:nth-child(1) > p').text();
}

function parserKeyword() {
    return $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-10 > a:nth-child(1) > h5').text();
}

function parserImage() {
    let dom = $('body > div.wrapper.wrapper--alt > section > div.container > header > div:nth-child(2) > div > div > div.col-md-2.img-thumb > img');
    if(!dom){
        return '';
    }
    return $(dom).attr('src');
}


try {
    var $ = cheerio.load(htmlString);
    result = parser();
    if(result.rows){
        result.code =Const._RETCODE_SUCCESS;
    }

    parserInfo.index = _INDEX;
    parserInfo.type = _TYPE;
} catch (e) {
    log(`Parsing Exception:${e.message}`,config.LOG._LOG_LEVEL_ERROR);
    result.code = Const._RETCODE_HANDLER_FAILED;
}

